import { Transaction } from "rclink/lib";
import { useUserStoreHook } from "/@/store/modules/user";

const SHA1withECDSA = "SHA1withECDSA";

export interface IKeyPair {
  ownerCreditCode: string;
  privateKey: string;
  certPEM: string;
  certName: string;
  publicKey: string;
}

export enum TranType {
  // 用户注册，权限合约
  Authority = "RdidOperateAuthorizeTPL",
  // 文物相关合约
  Antique = "CREvidence"
}

export enum FuncName {
  // 启用或禁用用户
  DISABLE_OR_ENABLE = "disableSigner",
  // 注册用户
  SIGN_UP_SIGNER = "signUpSigner",
  // 授权
  GRANT_OPERATE = "grantOperate",
  // 文物合约方法
  PUT_PROOF = "put_proof"
}

const getVersion = (chaincodeName: TranType) => {
  if (chaincodeName === TranType.Antique) {
    return useUserStoreHook().chainCodeVersion;
  }
  return 1;
};

const txToInvokeConsArgs = (
  data: string,
  funcName: FuncName,
  chaincodeName: TranType
) => ({
  type: "CHAINCODE_INVOKE",
  chaincodeName: chaincodeName,
  chaincodeVersion: getVersion(chaincodeName),
  chaincodeInvokeParams: {
    chaincodeFunction: funcName,
    chaincodeFunctionArgs: [data]
  }
});

export const transaction = (
  data: string,
  funcName: FuncName,
  chaincodeName: TranType
) => {
  const txToInvoke = new Transaction(
    txToInvokeConsArgs(data, funcName, chaincodeName)
  );
  return txToInvoke
    .sign({
      prvKey: useUserStoreHook().privateKey,
      pubKey: useUserStoreHook().publicKey,
      alg: SHA1withECDSA,
      creditCode: useUserStoreHook().creditCode,
      certName: useUserStoreHook().certName,
      provider: "jsrsasign"
    })
    .toString("hex");
};
